package org.omlite.controllers;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.view.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.AjaxBehaviorEvent;
import javax.servlet.http.HttpServletRequest;
import org.omlite.domain.db.OrkestManagerDB;
import org.omlite.util.gmail.SendGMailSSL;
import org.omlite.domain.models.AbsenceModel;
import org.omlite.domain.models.AdminModel;
import org.omlite.domain.models.ContactsModel;
import org.omlite.domain.models.DatesModel;
import org.omlite.domain.models.InviteesModel;
import org.omlite.domain.models.ProjectModel;
import org.omlite.domain.models.SubscriptionsModel;
import org.primefaces.context.RequestContext;
import org.primefaces.model.chart.CartesianChartModel;

/**
 *
 * @author Peter Hendriks 2012
 */
@ManagedBean
@ViewScoped
public class IndexController implements Serializable
{

    /**
     * Private Variables
     */
    private static final Logger log = Logger.getLogger(IndexController.class.getName());

    private final HttpServletRequest request;
    private final StringBuilder contextURL;
    private int selectedContactID;

    private ArrayList<DatesModel> datesModel,
            dates;
    private ArrayList<InviteesModel> contactsToBeMailed;
    private ArrayList<ContactsModel> contactsModel;
    private ArrayList<ContactsModel> filteredContacts;
    private ArrayList<SubscriptionsModel> subscriptionsModel;
    private ArrayList<AbsenceModel> absenceModel,
            presenceModel;
    private ArrayList projectNames,
            contactFullNames,
            recipients,
            changedDates;

    private ContactsModel selectedContact;
    private DatesModel newDate;
    private DatesModel selectedDate;
    private SendGMailSSL mail;
    private OrkestManagerDB db;
    private CartesianChartModel bezettingsModel;
    private AdminModel scModel;
    private AdminModel bcModel;
    private ProjectModel newProject;

    //Dit kan grotendeels worden vervangen door EL
    private boolean projectSaveButtonDisabled = true,
            loginPanelRendered,
            inputNewRendered,
            inputMembersRendered,
            afmeldLoginRendered,
            userPanelRendered,
            memberSelectRendered,
            adminLoginPanelRendered,
            adminMainPanelRendered,
            allDatesSelected,
            allContactsToBeMailedSelected,
            projectActive,
            dateSaveButtonDisabled;

    private int contactID,
            currentTab,
            selectedProjectRequiredPresence;

    private String header,
            invitationMSG,
            welcomeMSG,
            selectedProjectName,
            selectedProjectStartDate,
            selectedProjectEndDate,
            selectedProjectRepertoire,
            contactInstrument,
            contactFirstName,
            contactLastName,
            contactEmail,
            contactPhone,
            contactNote,
            usrName,// = "vuko",
            pwd, //= "keuris",
            selectedMember,
            //            Temp
            adminUsr,// = "vuko.strijkerschef",
            adminPwd,// = "strijkerschef",  
            mailSender,
            mailSenderPwd;

    //<editor-fold defaultstate="collapsed" desc="Getters & Setters">  
    public int getSelectedProjectRequiredPresence()
    {
        return selectedProjectRequiredPresence;
    }

    public void setSelectedProjectRequiredPresence(int selectedProjectRequiredPresence)
    {
        this.selectedProjectRequiredPresence = selectedProjectRequiredPresence;
    }

    public ArrayList<AbsenceModel> getPresenceModel()
    {
        return presenceModel;
    }

    public void setPresenceModel(ArrayList<AbsenceModel> presenceModel)
    {
        this.presenceModel = presenceModel;
    }

    public DatesModel getSelectedDate()
    {
        return selectedDate;
    }

    public void setSelectedDate(DatesModel selectedDate)
    {
        this.selectedDate = selectedDate;
    }

    public ProjectModel getNewProject()
    {
        return newProject;
    }

    public ArrayList<DatesModel> getDates()
    {
        return dates;
    }

    public void setDates(ArrayList<DatesModel> dates)
    {
        this.dates = dates;
    }

    public DatesModel getNewDate()
    {
        return newDate;
    }

    public void setNewDate(DatesModel newDate)
    {
        this.newDate = newDate;
    }

    public void setNewProject(ProjectModel newProject)
    {
        this.newProject = newProject;
    }

    public boolean isDateSaveButtonDisabled()
    {
        return dateSaveButtonDisabled;
    }

    public void setDateSaveButtonDisabled(boolean dateSaveButtonDisabled)
    {
        this.dateSaveButtonDisabled = dateSaveButtonDisabled;
    }

    public AdminModel getScModel()
    {
        return scModel;
    }

    public void setScModel(AdminModel scModel)
    {
        this.scModel = scModel;
    }

    public AdminModel getBcModel()
    {
        return bcModel;
    }

    public void setBcModel(AdminModel bcModel)
    {
        this.bcModel = bcModel;
    }

    public String getHeader()
    {
        return header;
    }

    public void setHeader(String header)
    {
        this.header = header;
    }

    public boolean isProjectSaveButtonDisabled()
    {
        return projectSaveButtonDisabled;
    }

    public void setProjectSaveButtonDisabled(boolean projectSaveButtonDisabled)
    {
        this.projectSaveButtonDisabled = projectSaveButtonDisabled;
    }

    public ContactsModel getSelectedContact()
    {
        return selectedContact;
    }

    public void setSelectedContact(ContactsModel selectedContact)
    {
        this.selectedContact = selectedContact;
    }

    public CartesianChartModel getBezettingsModel()
    {
        return bezettingsModel;
    }

    public void setBezettingsModel(CartesianChartModel bezettingsModel)
    {
        this.bezettingsModel = bezettingsModel;
    }

    public String getWelcomeMSG()
    {
        return welcomeMSG;
    }

    public void setWelcomeMSG(String welcomeMSG)
    {
        this.welcomeMSG = welcomeMSG;
    }

    private boolean isStringPlayer(String instrument)
    {
        return instrument.equalsIgnoreCase("viool")
                || instrument.equalsIgnoreCase("altviool")
                || instrument.equalsIgnoreCase("cello")
                || instrument.equalsIgnoreCase("contrabas");
    }

    public String getMailSender()
    {
        return mailSender;
    }

    public void setMailSender(String mailSender)
    {
        this.mailSender = mailSender;
    }

    public ArrayList<AbsenceModel> getAbsenceModel()
    {
        return absenceModel;
    }

    public void setAbsenceModel(ArrayList<AbsenceModel> absenceModel)
    {
        this.absenceModel = absenceModel;
    }

    public ArrayList<SubscriptionsModel> getSubscriptionsModel()
    {
        return subscriptionsModel;
    }

    public void setSubscriptionsModel(ArrayList<SubscriptionsModel> subscriptionsModel)
    {
        this.subscriptionsModel = subscriptionsModel;
    }

    public String getContactNote()
    {
        return contactNote;
    }

    public void setContactNote(String contactNote)
    {
        this.contactNote = contactNote;
    }

    public ArrayList<ContactsModel> getFilteredContacts()
    {
        return filteredContacts;
    }

    public void setFilteredContacts(ArrayList<ContactsModel> filteredContacts)
    {
        this.filteredContacts = filteredContacts;
    }

    public ArrayList<ContactsModel> getContactsModel()
    {
        return contactsModel;
    }

    public void setContactsModel(ArrayList<ContactsModel> contactsModel)
    {
        this.contactsModel = contactsModel;
    }

    public boolean isProjectActive()
    {
        return projectActive;
    }

    public void setProjectActive(boolean projectActive)
    {
        this.projectActive = projectActive;
    }

    public boolean isAllContactsToBeMailedSelected()
    {
        return allContactsToBeMailedSelected;
    }

    public void setAllContactsToBeMailedSelected(boolean allContactsToBeMailedSelected)
    {
        this.allContactsToBeMailedSelected = allContactsToBeMailedSelected;
    }

    public boolean isAllDatesSelected()
    {
        return allDatesSelected;
    }

    public void setAllDatesSelected(boolean allDatesSelected)
    {
        this.allDatesSelected = allDatesSelected;
    }

    public String getInvitationMSG()
    {
        return invitationMSG;
    }

    public void setInvitationMSG(String invitationMSG)
    {
        this.invitationMSG = invitationMSG;
    }

    public ArrayList getRecipients()
    {
        return recipients;
    }

    public void setRecipients(ArrayList recipients)
    {
        this.recipients = recipients;
    }

    public ArrayList<InviteesModel> getContactsToBeMailed()
    {
        return contactsToBeMailed;
    }

    public void setContactsToBeMailed(ArrayList<InviteesModel> contactsToBeMailed)
    {
        this.contactsToBeMailed = contactsToBeMailed;
    }

    public boolean isAdminMainPanelRendered()
    {
        return adminMainPanelRendered;
    }

    public void setAdminMainPanelRendered(boolean adminMainPanelRendered)
    {
        this.adminMainPanelRendered = adminMainPanelRendered;
    }

    public boolean isAdminLoginPanelRendered()
    {
        return adminLoginPanelRendered;
    }

    public void setAdminLoginPanelRendered(boolean adminLoginPanelRendered)
    {
        this.adminLoginPanelRendered = adminLoginPanelRendered;
    }

    public String getAdminUsr()
    {
        return adminUsr;
    }

    public void setAdminUsr(String adminUsr)
    {
        this.adminUsr = adminUsr;
    }

    public String getAdminPwd()
    {
        return adminPwd;
    }

    public void setAdminPwd(String adminPwd)
    {
        this.adminPwd = adminPwd;
    }

    public boolean isMemberSelectRendered()
    {
        return memberSelectRendered;
    }

    public void setMemberSelectRendered(boolean memberSelectRendered)
    {
        this.memberSelectRendered = memberSelectRendered;
    }

    public int getCurrentTab()
    {
        return currentTab;
    }

    public void setCurrentTab(int currentTab)
    {
        this.currentTab = currentTab;
    }

    public String getSelectedMember()
    {
        return selectedMember;
    }

    public void setSelectedMember(String selectedMember)
    {
        this.selectedMember = selectedMember;
    }

    public ArrayList getContactFullNames()
    {
        return contactFullNames;
    }

    public void setContactFullNames(ArrayList contactFullNames)
    {
        this.contactFullNames = contactFullNames;
    }

    public boolean isInputMembersRendered()
    {
        return inputMembersRendered;
    }

    public void setInputMembersRendered(boolean inputMembersRendered)
    {
        this.inputMembersRendered = inputMembersRendered;
    }

    public boolean isUserPanelRendered()
    {
        return userPanelRendered;
    }

    public void setUserPanelRendered(boolean userPanelRendered)
    {
        this.userPanelRendered = userPanelRendered;
    }

    public String getUsrName()
    {
        return usrName;
    }

    public void setUsrName(String usrName)
    {
        this.usrName = usrName;
    }

    public String getPwd()
    {
        return pwd;
    }

    public void setPwd(String pwd)
    {
        this.pwd = pwd;
    }

    public boolean isAfmeldLoginRendered()
    {
        return afmeldLoginRendered;
    }

    public void setAfmeldLoginRendered(boolean afmeldLoginRendered)
    {
        this.afmeldLoginRendered = afmeldLoginRendered;
    }

    public String getContactInstrument()
    {
        return contactInstrument;
    }

    public void setContactInstrument(String contactInstrument)
    {
        this.contactInstrument = contactInstrument;
    }

    public String getContactFirstName()
    {
        return contactFirstName;
    }

    public void setContactFirstName(String contactFirstName)
    {
        this.contactFirstName = contactFirstName;
    }

    public String getContactLastName()
    {
        return contactLastName;
    }

    public void setContactLastName(String contactLastName)
    {
        this.contactLastName = contactLastName;
    }

    public String getContactEmail()
    {
        return contactEmail;
    }

    public void setContactEmail(String contactEmail)
    {
        this.contactEmail = contactEmail;
    }

    public String getContactPhone()
    {
        return contactPhone;
    }

    public void setContactPhone(String contactPhone)
    {
        this.contactPhone = contactPhone;
    }

    public ArrayList<DatesModel> getDatesModel()
    {
        return datesModel;
    }

    public void setDatesModel(ArrayList<DatesModel> datesModel)
    {
        this.datesModel = datesModel;
    }

    public boolean isInputNewRendered()
    {
        return inputNewRendered;
    }

    public String getSelectedProjectName()
    {
        return selectedProjectName;
    }

    public void setSelectedProjectName(String selectedProjectName)
    {
        this.selectedProjectName = selectedProjectName;
    }

    public String getSelectedProjectStartDate()
    {
        return selectedProjectStartDate;
    }

    public void setSelectedProjectStartDate(String selectedProjectStartDate)
    {
        this.selectedProjectStartDate = selectedProjectStartDate;
    }

    public String getSelectedProjectEndDate()
    {
        return selectedProjectEndDate;
    }

    public void setSelectedProjectEndDate(String selectedProjectEndDate)
    {
        this.selectedProjectEndDate = selectedProjectEndDate;
    }

    public String getSelectedProjectRepertoire()
    {
        return selectedProjectRepertoire;
    }

    public void setSelectedProjectRepertoire(String selectedProjectRepertoire)
    {
        this.selectedProjectRepertoire = selectedProjectRepertoire;
    }

    public boolean isLoginPanelRendered()
    {
        return loginPanelRendered;
    }

    public ArrayList getProjectNames()
    {
        return projectNames;
    }

    //</editor-fold>
    public IndexController()
    {
        request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
        contextURL = new StringBuilder(request.getRequestURL().toString().replace(request.getRequestURI().substring(0), ""));
        contextURL.append(request.getContextPath());
        afmeldLoginRendered = true;
        memberSelectRendered = true;
        adminLoginPanelRendered = true;
        //set to true to debug
        db = new OrkestManagerDB("orkest.db", true);
        header = db.getTextLabel("header");
        welcomeMSG = db.getTextLabel("welcomeMSG");
        projectNames = db.getAllProjectInfo("projectName");
        try
        {
            if (request !=null
                    ||request.getParameter("u") !=null
                    || request.getParameter("p") != null
                    || request.getParameter("name") !=null
                    && request.getParameter("u").equals("vuko")
                    && request.getParameter("p").equals("keuris")
                    && !request.getParameter("name").equals(""))
            {
                usrName = "vuko";
                pwd = "keuris";
                selectedMember = request.getParameter("name");
                userLogin();
                memberSelectRendered = false;
                currentTab = 1;
            }
        } catch (Exception e)
        {
            log.log(Level.WARNING, e.getMessage());
            e.printStackTrace();
        }

    }

    private void senderCheck(String instrument)
    {
        scModel = db.getAdminInfo("strijkerschef");
        bcModel = db.getAdminInfo("blazerschef");
        if (this.isStringPlayer(instrument))
        {
            mailSender = scModel.getEmail();
            mailSenderPwd = scModel.getPassword();
        } else
        {
            mailSender = bcModel.getEmail();
            mailSenderPwd = bcModel.getPassword();
        }
    }


    /**
     * For the New Members section only!
     */
    public void selectProjectNewSubscribtion()
    {
        try
        {
            if (!selectedProjectName.equalsIgnoreCase("empty"))
            {
                selectedProjectStartDate = db.getProjectInfo("projectStartDate", selectedProjectName);
                selectedProjectEndDate = db.getProjectInfo("projectEndDate", selectedProjectName);
                selectedProjectRepertoire = db.getProjectInfo("projectRepertoire", selectedProjectName);
                inputNewRendered = true;
                //0 betekent dat het bestuur deze data heeft toegevoegd
                datesModel = db.getDates(db.getProjectID(selectedProjectName), 0);
            } else
            {
                inputNewRendered = false;
            }
        } catch (Exception e)
        {
            log.log(Level.WARNING, e.getMessage());
            throw new RuntimeException(e);
        }
    }

    /**
     * For existing members
     */
    public void selectProjectForMembers()
    {
        try
        {
            if (!selectedProjectName.equalsIgnoreCase("empty"))
            {
                selectedProjectStartDate = db.getProjectInfo("projectStartDate", selectedProjectName);
                selectedProjectEndDate = db.getProjectInfo("projectEndDate", selectedProjectName);
                selectedProjectRepertoire = db.getProjectInfo("projectRepertoire", selectedProjectName);
                inputMembersRendered = true;
                ArrayList cInfo = db.getContactInfoByFullName(selectedMember);
                contactID = Integer.parseInt(cInfo.get(0).toString());
                contactInstrument = cInfo.get(1).toString();
                contactFirstName = cInfo.get(2).toString();
                contactLastName = cInfo.get(3).toString();
                contactEmail = cInfo.get(4).toString();
                contactPhone = cInfo.get(5).toString();
                datesModel = db.getDates(db.getProjectID(selectedProjectName), contactID);
                changedDates = new ArrayList();
                if (datesModel.isEmpty())
                {
                    datesModel = db.getDates(db.getProjectID(selectedProjectName), 0);
                }
            } else
            {
                inputMembersRendered = false;
            }
        } catch (Exception e)
        {
            log.log(Level.WARNING, e.getMessage());
            throw new RuntimeException(e);
        }
        currentTab = 1;
    }

    /**
     * For Admin users
     */
    public void selectProjectForAdministrators()
    {
        try
        {
            if (!selectedProjectName.equalsIgnoreCase("empty"))
            {
                selectedProjectStartDate = db.getProjectInfo("projectStartDate", selectedProjectName);
                selectedProjectEndDate = db.getProjectInfo("projectEndDate", selectedProjectName);
                selectedProjectRepertoire = db.getProjectInfo("projectRepertoire", selectedProjectName);
                subscriptionsModel = db.getSubscriptions(selectedProjectName);
                absenceModel = db.getAbsence(selectedProjectName);
                presenceModel = db.getPresence(selectedProjectName);
                selectedProjectRequiredPresence = Integer.parseInt(db.getProjectInfo("requiredPresence", selectedProjectName));
                projectSaveButtonDisabled = false;
                dates = db.getDates(db.getProjectID(selectedProjectName), 0);
                newDate = new DatesModel();
                newDate.setProjectID(0);
                newDate.setContactID(0);
                newDate.setPresent(false);
                if (db.getProjectInfo("active", selectedProjectName).equalsIgnoreCase("true"))
                {
                    projectActive = true;
                    contactsToBeMailed = db.getAllContactsToInvite();
                } else
                {
                    projectActive = false;
                }
            } else
            {
                selectedProjectStartDate = null;
                selectedProjectEndDate = null;
                selectedProjectRepertoire = null;
                subscriptionsModel = null;
                absenceModel = null;
                projectActive = false;
                projectSaveButtonDisabled = true;
            }
        } catch (Exception e)
        {
            log.log(Level.WARNING, e.getMessage());
            throw new RuntimeException(e);
        }
        currentTab = 2;
    }

    public void saveNewMember()
    {
        if (!db.contactExists(contactEmail)
                && contactEmail.contains("@")
                && !contactEmail.contains(" ")
                && db.SaveNewMember(db.getProjectID(selectedProjectName), contactInstrument.toLowerCase().replace(" ", ""), contactFirstName, contactLastName, contactEmail, contactPhone, datesModel))
        {
            StringBuilder sb = new StringBuilder("Bedankt ");
            sb.append(contactFirstName);
            sb.append("! Je bent nu ingeschreven om ");
            sb.append(contactInstrument);
            sb.append(" te spelen tijdens het project '");
            sb.append(selectedProjectName);
            sb.append("'! Tot snel!");
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(sb.toString()));
            inputNewRendered = false;
            new Thread(() ->
            {
                while (true)
                {
                    try
                    {
                        StringBuilder msg;
                        msg = new StringBuilder("Beste ");
                        msg.append(contactFirstName);
                        msg.append(",\n\n");
                        msg.append("Goed dat je je hebt aangemeld voor het project '");
                        msg.append(selectedProjectName);
                        msg.append("' van het VU-Kamerorkest! We zijn blij dat je bij ons ");
                        msg.append(contactInstrument);
                        msg.append(" wil komen spelen.");
                        msg.append("Het kan zijn dat we je vragen om auditie te doen. Dit zal informeel gebeuren hier zullen o.a. de dirigent en de concertmeester bij aanwezig zijn.\n");
                        msg.append("Wees hier niet zenuwachtig voor, het is slechts een formaliteit en we hebben het allemaal gedaan.");
                        msg.append("We nemen contact met je op over eventuele auditietijden, tot die tijd vind je meer informatie op www.vuko.nl .\n\n");
                        msg.append("Wil je je in de toekomst afmelden voor repetities dan kan dat via de volgende link: \n\n");
                        msg.append(contextURL.toString());
                        msg.append("/index.xhtml?u=vuko&p=keuris&name=");
                        msg.append(contactFirstName.replace(" ", "_"));
                        msg.append("%20");
                        msg.append(contactLastName.replace(" ", "_"));
                        msg.append("\n\nMocht de link niet werken dan kun je ook inloggen met \n\nGebruikersnaam: vuko\nWachtwoord: keuris\n\n");
                        msg.append("Het wordt zeker een mooi project en we zijn blij dat jij er bij wil zijn!\n\n");
                        msg.append("Tot snel,\n\n\n");
                        msg.append("Bestuur VU-Kamerorkest\n(dit bericht werd automatisch gegenereerd)");
                        
                        senderCheck(contactInstrument);
                        mail = new SendGMailSSL(mailSender, mailSenderPwd);
                        mail.Send(contactEmail, mailSender, "Inschrijving VUKO "
                                + selectedProjectName, msg.toString());
                        
                        senderCheck(contactInstrument);
                        mail = new SendGMailSSL(mailSender, mailSenderPwd);
                        mail.Send(mailSender, mailSender, "Inschrijving nieuwe "
                                + contactInstrument, "Ingeschreven: "
                                        + contactFirstName
                                        + " "
                                        + contactLastName
                                        + "\nSpeelt: "
                                        + contactInstrument
                                        + "\nEmail: "
                                        + contactEmail
                                        + "\nTelefoon: "
                                        + contactPhone
                                        + "\nBeschikbaarheid: "
                                        + contextURL.toString()
                                        + "/index.xhtml?u=vuko&p=keuris&name="
                                        + contactFirstName.replace(" ", "_")
                                        + "%20"
                                        + contactLastName.replace(" ", "_")
                                        + "\n\n Controleer auditiebeleid!\n(dit bericht werd automatisch gegenereerd)");
                    } catch (Exception e)
                    {
                        log.log(Level.WARNING, e.getMessage());
                        throw new RuntimeException(e);
                    }
                    break;
                }
            }).start();
        } else
        {
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage("Er ging iets mis, zijn alle gegevens wel correct ingevuld? Het zou ook kunnen dat je al staat geregistreerd. Gebruik dan het tabblad 'Herinschrijven/Afmelden'."));
        }
        mail = null;
        RequestContext.getCurrentInstance().scrollTo("mainForm");
    }

    //Saving the info and data of an existing project by members...
    public void saveExistingMemberAndDates()
    {
        int dateSelectionCount = 0;
        int concertCount = 0;
        for (DatesModel dm : datesModel)
        {
            if (dm.isPresent())
            {
                dateSelectionCount++;
            }
            if (dm.getLocation().toLowerCase().contains("concert"))
            {
                concertCount++;
            }
        }
        int nOfRehersals = datesModel.size() - concertCount;
        int currentPercentage = Math.round(dateSelectionCount * 100 / nOfRehersals);
        if (currentPercentage < Integer.parseInt(db.getProjectInfo("requiredPresence", selectedProjectName)) && this.isStringPlayer(contactInstrument))
        {
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage("Met het huidig aantal geselecteerde data heb je een aanwezigheidspercentage van "
                            + currentPercentage
                            + " procent.\n\nVoor deelname is minimaal "
                            + db.getProjectInfo("requiredPresence", selectedProjectName)
                            + "% aanwezigheid vereist!"));
            RequestContext.getCurrentInstance().scrollTo(":mainForm");
        } else
        {
            if (contactEmail.contains("@")
                    && !contactEmail.contains(" ")
                    && db.SaveExistingMemberAndDates(contactID,
                            db.getProjectID(selectedProjectName),
                            contactInstrument.toLowerCase().replace(" ", ""),
                            contactFirstName,
                            contactLastName,
                            contactEmail,
                            contactPhone,
                            datesModel))
            {
                StringBuilder msg = new StringBuilder("Bedankt ");
                msg.append(contactFirstName);
                msg.append("! Je gegevens en aanwezigheid zijn bijgewerkt, tot snel!");
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(msg.toString()));
                inputMembersRendered = false;
                new Thread(() ->
                {
                    while (true)
                    {
                        try
                        {
                            StringBuilder msg1 = new StringBuilder("Beste Chef,\n\n");
                            msg1.append(contactFirstName);
                            msg1.append(" ");
                            msg1.append(contactLastName);
                            msg1.append(" heeft zijn/haar gegevens en/of beschikbaarheid gewijzigd.\nSpeelt: ");
                            msg1.append(contactInstrument);
                            msg1.append("\nEmail: ");
                            msg1.append(contactEmail);
                            msg1.append("\nTelefoon: ");
                            msg1.append(contactPhone);
                            msg1.append("\nWijzigingen: ");
                            msg1.append(changedDates.toString());
                            msg1.append("\n\nURL Beschikbaarheid: ");
                            msg1.append(contextURL.toString());
                            msg1.append("/index.xhtml?u=vuko&p=keuris&name=");
                            msg1.append(contactFirstName.replace(" ", "_"));
                            msg1.append("%20");
                            msg1.append(contactLastName.replace(" ", "_"));
                            senderCheck(contactInstrument);
                            mail = new SendGMailSSL(mailSender, mailSenderPwd);
                            mail.Send(mailSender, mailSender, "Wijziging beschikbaarheid " + contactFirstName + " " + contactLastName, msg1.toString());
                        }catch (Exception e)
                        {
                            log.log(Level.WARNING, e.getMessage());
                            throw new RuntimeException(e);
                        }
                        break;
                    }
                }).start();
            } else
            {
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Er ging iets mis, zijn alle gegevens wel correct ingevuld?"));
            }
        }
        currentTab = 1;
        RequestContext.getCurrentInstance().scrollTo(":mainForm");
    }

    public void userLogin()
    {
        currentTab = 1;
        if (usrName.equals("") && pwd.equals(""))
        {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Gebruikersnaam en Wachtwoord zijn vereist!"));
        } else
        {
            if (usrName.toLowerCase().equals("vuko") && pwd.toLowerCase().equals("keuris"))
            {
                afmeldLoginRendered = false;
                userPanelRendered = true;
                contactFullNames = db.getAllContactsFullNames();
            } else
            {
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Gebruikersnaam en/of Wachtwoord werden niet herkend!"));
            }
        }
    }

    public void adminLogin()
    {
        currentTab = 2;
        if (adminUsr.equals("") && adminPwd.equals(""))
        {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Gebruikersnaam en Wachtwoord zijn vereist!"));
        } else
        {
            if (adminUsr.toLowerCase().equals("vuko.strijkerschef")
                    && adminPwd.equalsIgnoreCase("strijkerschef")
                    || adminUsr.equalsIgnoreCase("vuko.blazerschef")
                    && adminPwd.equalsIgnoreCase("toeter01"))
            {
                adminLoginPanelRendered = false;
                adminMainPanelRendered = true;
                contactsModel = db.getAllContacts();
                invitationMSG = db.getTextLabel("invitationMSG");
                scModel = db.getAdminInfo("strijkerschef");
                bcModel = db.getAdminInfo("blazerschef");
                //newProject = new ProjectModel(0, 0, "", "", "", "", false);
                newProject = new ProjectModel();
                newProject.setId(0);
                newProject.setRequiredPresence(0);
                newProject.setActive(false);

            } else
            {
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Gebruikersnaam en/of Wachtwoord werden niet herkend!"));
            }
        }
    }

    public void inviteMembers()
    {
        new Thread(() ->
        {
            while (true)
            {
                contactsToBeMailed.stream().forEach((contact) ->
                {
                    try
                    {
                        if (contact.isInvited())
                        {
                            String workMSG = invitationMSG;
                            StringBuilder personalURL = new StringBuilder(contextURL.toString());
                            personalURL.append("/index.xhtml?u=vuko&p=keuris&name=");
                            personalURL.append(contact.getContactFirstName().replace(" ", "_"));
                            personalURL.append("%20");
                            personalURL.append(contact.getContactLastName().replace(" ", "_"));
                            workMSG = workMSG.replace("#!#contactFirstName#!#", contact.getContactFirstName());
                            workMSG = workMSG.replace("#!#selectedProjectName#!#", selectedProjectName);
                            workMSG = workMSG.replace("#!#selectedProjectRepertoire#!#", selectedProjectRepertoire);
                            workMSG = workMSG.replace("#!#selectedProjectStartDate#!#", selectedProjectStartDate);
                            workMSG = workMSG.replace("#!#selectedProjectEndDate#!#", selectedProjectEndDate);
                            workMSG = workMSG.replace("#!#personalURL#!#", personalURL.toString());
                            workMSG = workMSG.replace("#!#contactInstrument#!#", contact.getContactInstrument());
                            senderCheck(contact.getContactInstrument());
                            mail = new SendGMailSSL(mailSender, mailSenderPwd);
                            mail.Send(contact.getEmail(), mailSender, "Deelname VUKO " + selectedProjectName, workMSG);
                            log.log(Level.INFO, "Mail naar: {0} van: {1}Project: {2}Bericht: {3}", new Object[]{contact.getEmail(), mailSender, selectedProjectName, workMSG});
                        }
                    } catch (Exception e)
                    {
                        log.log(Level.WARNING, e.getMessage());
                        throw new RuntimeException(e);
                    }
                });
                break;
            }
        }).start();
        FacesContext.getCurrentInstance().addMessage(null,
                new FacesMessage("Emails worden verstuurd naar: "
                        + recipients));
    }

    public void sortInvitees()
    {
        recipients = new ArrayList();
        contactsToBeMailed.stream().filter((contact) -> (contact.isInvited())).forEach((contact) ->
        {
            recipients.add(contact.getContactFirstName()
                    + " "
                    + contact.getContactLastName());
        });
    }

    public void selectAllDates()
    {
        datesModel.stream().forEach((date) ->
        {
            if (allDatesSelected)
            {
                date.setPresent(true);
            } else
            {
                date.setPresent(false);
            }
        });
    }

    public void selectAllInvitees()
    {
        contactsToBeMailed.stream().forEach((InviteesModel contact) ->
        {
            if (allContactsToBeMailedSelected)
            {
                contact.setInvited(true);
            } else
            {
                contact.setInvited(false);
            }
        });
    }

    public void saveNewContact()
    {
        if (!contactEmail.contains(" ")
                && !contactFirstName.equals("")
                && db.newContactSaved(contactFirstName,
                        contactLastName,
                        contactInstrument.toLowerCase().replace(" ", ""),
                        contactPhone,
                        contactEmail,
                        contactNote.replace("'", "#!#")))
        {
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage("Nieuwe contactpersoon '"
                            + contactFirstName
                            + " "
                            + contactLastName
                            + "' opgeslagen."));
            contactsModel = db.getAllContacts();
            contactFirstName = null;
            contactLastName = null;
            contactInstrument = null;
            contactPhone = null;
            contactEmail = null;
            contactNote = null;
        } else
        {
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage("Er ging iets mis, bestaat deze contactpersoon al?"));
        }
    }

    public void saveExistingProject()
    {
        if (!selectedProjectStartDate.isEmpty()
                && !selectedProjectEndDate.isEmpty()
                && !selectedProjectRepertoire.isEmpty()
                && selectedProjectRequiredPresence != 0)
        {
            try
            {
                db.saveSelectedProject(selectedProjectStartDate,
                        selectedProjectEndDate,
                        selectedProjectRepertoire,
                        projectActive,
                        selectedProjectRequiredPresence,
                        selectedProjectName);
                projectNames = db.getAllProjectInfo("projectName");
                FacesContext.getCurrentInstance().addMessage(null,
                        new FacesMessage("Project: '" + selectedProjectName + "' opgeslagen."));
            } catch (Exception e)
            {
                log.log(Level.WARNING, e.getMessage());
                FacesContext.getCurrentInstance().addMessage(null,
                        new FacesMessage("Er ging iets mis, zijn alle velden ingevuld?"));
                throw new RuntimeException(e);
            }

        }
    }

    public void warnBeforeDisabeling()
    {
        FacesContext.getCurrentInstance().addMessage(null,
                new FacesMessage(FacesMessage.SEVERITY_WARN,
                        "Let Op!<br/><br/>Als je nu op opslaan klikt, verdwijnt onderstaand project uit de lijst wanneer je deze pagina ververst.<br/><br/>Is het project voorbij en kan het echt worden gedeactiveerd, klik dan op 'Opslaan'.", null));
    }

    public void saveWelcomeMSG()
    {
        try
        {
            db.saveTextLabel("welcomeMSG", welcomeMSG);
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_INFO,
                            "Welkomsttekst Gewijzigd.", null));
        } catch (Exception e)
        {
            log.log(Level.WARNING, e.getMessage());
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_FATAL,
                            "Er ging iets mis!<br/><br/>" + e.getMessage(), null));
            throw new RuntimeException(e);
        }
    }

    public void saveInvitationMSG()
    {
        try
        {
            db.saveTextLabel("invitationMSG", invitationMSG);
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_INFO,
                            "Uitnodigingstekst Gewijzigd.", null));
        } catch (Exception e)
        {
            log.log(Level.WARNING, e.getMessage());
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_FATAL,
                            "Er ging iets mis!<br/><br/>" + e.getMessage(), null));
            throw new RuntimeException(e);
        }
    }

    public void saveAdminEmail()
    {
        try
        {
            if (scModel.getEmail().toLowerCase().contains("gmail")
                    && bcModel.getEmail().toLowerCase().contains("gmail")
                    && !scModel.getEmail().isEmpty()
                    && !scModel.getEmail().isEmpty())
            {
                db.saveAdminMail(scModel, bcModel);
                FacesContext.getCurrentInstance().addMessage(null,
                        new FacesMessage(FacesMessage.SEVERITY_INFO,
                                "Gmail adressen Gewijzigd.", null));
            }
        } catch (Exception e)
        {
            log.log(Level.WARNING, e.getMessage());
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_FATAL,
                            "Er ging iets mis!<br/><br/>" + e.getMessage(), null));
            throw new RuntimeException(e);
        }
    }

    public void removeContact()
    {
        try
        {
            if (!selectedContact.getFirstName().isEmpty())
            {
                db.removeContact(selectedContact);
                contactsModel = db.getAllContacts();
                FacesContext.getCurrentInstance().addMessage(null,
                        new FacesMessage(FacesMessage.SEVERITY_INFO,
                                selectedContact.getFirstName()
                                + " "
                                + selectedContact.getLastName()
                                + " verwijderd!", null));
            } else
            {
                FacesContext.getCurrentInstance().addMessage(null,
                        new FacesMessage(FacesMessage.SEVERITY_ERROR,
                                "Er ging iets mis...", null));
            }
        } catch (Exception e)
        {
            log.log(Level.WARNING, e.getMessage());
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_FATAL,
                            "Er ging iets mis!<br/><br/>" + e.getMessage(), null));
            throw new RuntimeException(e);
        }
    }

    public void selectContact()
    {
        try
        {
            selectedContactID = db.getContactID(selectedContact);
        } catch (Exception e)
        {
            log.log(Level.WARNING, e.getMessage());
            throw new RuntimeException(e);
        }
    }

    public void saveExistingContact()
    {
        try
        {
            if (!selectedContact.getFirstName().isEmpty()
                    && !selectedContact.getLastName().isEmpty()
                    && !selectedContact.getEmail().isEmpty()
                    && !selectedContact.getInstrument().isEmpty())
            {
                db.saveExistingContact(selectedContactID, selectedContact);
                contactsModel = db.getAllContacts();
                FacesContext.getCurrentInstance().addMessage(null,
                        new FacesMessage(FacesMessage.SEVERITY_INFO,
                                "Gegevens van "
                                + selectedContact.getFirstName()
                                + " "
                                + selectedContact.getLastName()
                                + " werden aangepast!", null));
            } else
            {
                FacesContext.getCurrentInstance().addMessage(null,
                        new FacesMessage(FacesMessage.SEVERITY_ERROR,
                                "Er ging iets mis...<br/><br/>Zijn alle velden ingevuld?", null));
            }
        } catch (Exception e)
        {
            log.log(Level.WARNING, e.getMessage());
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_FATAL,
                            "Er ging iets mis!<br/><br/>" + e.getMessage(), null));
            throw new RuntimeException(e);
        }
    }

    //Wordt uitgevoerd als er een vinkje wordt gezet of weggehaald.
    public void checkSelectedDateByMember(AjaxBehaviorEvent event)
    {
        try
        {
            DatesModel checkedDatesModel = (DatesModel) event.getComponent().getAttributes().get("checkedDatesModel");
            //Bijhouden wie wat wijzigt
            changedDates.add("\n\nBeschikbaarheid op "
                    + checkedDatesModel.getDate()
                    + " is nu: "
                    + checkedDatesModel.isPresent()
                    + "\n"
                    + checkedDatesModel.getCommentsByContact());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date dateSelected = sdf.parse(checkedDatesModel.getDate());
            Date today = new Date();
            if (dateSelected.before(today) && checkedDatesModel.isPresent())
            {
                dateSaveButtonDisabled = true;
                FacesContext.getCurrentInstance().addMessage(null,
                        new FacesMessage(FacesMessage.SEVERITY_FATAL,
                                "Fout!<br/><br/>"
                                + "Het wijzigen van je beschikbaarheid op een repetitiedag zef of op data uit het verleden is niet toegestaan.<br/><br/>Ververs de pagina en probeer het opnieuw",
                                null));

            }
        } catch (Exception e)
        {
            log.log(Level.WARNING, e.getMessage());
            throw new RuntimeException(e);
        }
    }

    public void saveNewProject()
    {
        try
        {
            if (!newProject.getProjectStartDate().isEmpty()
                    && !newProject.getProjectEndDate().isEmpty()
                    && !newProject.getProjectName().isEmpty()
                    && !newProject.getProjectRepertoire().isEmpty()
                    && newProject.getRequiredPresence() != 0)
            {
                db.saveNewProject(newProject);
                projectNames = db.getAllProjectInfo("projectName");
                selectedProjectName = newProject.getProjectName();
                this.selectProjectForAdministrators();
                FacesContext.getCurrentInstance().addMessage(null,
                        new FacesMessage(FacesMessage.SEVERITY_INFO,
                                "Nieuw project '"
                                + newProject.getProjectName()
                                + "' opgeslagen!", null));
//                newProject = new ProjectModel(0, 0, "", "", "", "", false);
                newProject = new ProjectModel();
                newProject.setId(0);
                newProject.setRequiredPresence(0);
                newProject.setActive(false);
            } else
            {
                FacesContext.getCurrentInstance().addMessage(null,
                        new FacesMessage(FacesMessage.SEVERITY_ERROR,
                                "Er ging iets mis!<br/><br/>"
                                + "Zijn alle vereiste velden ingevuld?", null));
            }
        } catch (Exception e)
        {
            log.log(Level.WARNING, e.getMessage());
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_FATAL,
                            "Fout!<br/><br/>"
                            + e.getMessage(), null));
            throw new RuntimeException(e);
        }
    }

    public void saveNewDate()
    {
        try
        {
            newDate.setProjectID(db.getProjectID(selectedProjectName));
            if (newDate.getProjectID() != 0
                    && !newDate.getDate().isEmpty()
                    && !newDate.getStartTime().isEmpty()
                    && !newDate.getEndTime().isEmpty()
                    && !newDate.getLocation().isEmpty())
            {
                db.saveNewDate(newDate);
                dates = db.getDates(db.getProjectID(selectedProjectName), 0);
                FacesContext.getCurrentInstance().addMessage(null,
                        new FacesMessage(FacesMessage.SEVERITY_INFO,
                                "Nieuwe datum '"
                                + newDate.getDate()
                                + "' toegevoegd aan project '"
                                + selectedProjectName
                                + "'!", null));

                // newDate = new DatesModel(0, 0, "", "", "", "", "", "", false);
                newDate = new DatesModel();
                newDate.setProjectID(0);
                newDate.setContactID(0);
                newDate.setPresent(false);
            } else
            {
                FacesContext.getCurrentInstance().addMessage(null,
                        new FacesMessage(FacesMessage.SEVERITY_ERROR,
                                "Er ging iets mis!<br/><br/>"
                                + "Zijn alle vereiste velden ingevuld en is er een project geselecteerd?", null));
            }
        } catch (Exception e)
        {
            log.log(Level.WARNING, e.getMessage());
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_FATAL,
                            "Fout!<br/><br/>"
                            + e.getMessage(), null));
            throw new RuntimeException(e);
        }
    }

    public void delDate()
    {
        if (!selectedDate.getDate().isEmpty())
        {
            try
            {
                db.delDate(selectedDate);
                dates = db.getDates(db.getProjectID(selectedProjectName), 0);
                FacesContext.getCurrentInstance().addMessage(null,
                        new FacesMessage(FacesMessage.SEVERITY_INFO,
                                "Datum '"
                                + selectedDate.getDate()
                                + "' werd verwijderd.", null));
            } catch (Exception e)
            {
                log.log(Level.WARNING, e.getMessage());
                FacesContext.getCurrentInstance().addMessage(null,
                        new FacesMessage(FacesMessage.SEVERITY_FATAL,
                                "Fout!<br/><br/>"
                                + e.getMessage(), null));
                throw new RuntimeException(e);
            }
        } else
        {
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR,
                            "Er ging iets mis!", null));
        }
    }

    public void saveProjectDatesModel()
    {
        try
        {
            for (DatesModel date : dates)
            {
                db.updateProjectDates(date);
            }
            dates = db.getDates(db.getProjectID(selectedProjectName), 0);
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_INFO,
                            "Projectdata gewijzigd'", null));
        } catch (Exception e)
        {
            log.log(Level.WARNING, e.getMessage());
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_FATAL,
                            "Fout!<br/><br/>"
                            + e.getMessage(), null));
            throw new RuntimeException(e);
        }
    }

}
